package com.example.thread.demo.completablefuture;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFutureTask;

import javax.annotation.Nullable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @author zhy
 * @date 2020/5/18 6:25 下午
 * @description
 */
public class CallbackFutureTest {


    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // Guava ListenableFutureTask
        ListenableFutureTask<String> listenableFutureTask = ListenableFutureTask.create(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "你好，张海洋，这里是厦门趣店集团！";
            }
        });

        // 增加回调处理，注意这里要设置一个线程池参数哦
        Futures.addCallback(listenableFutureTask, new FutureCallback<String>() {
            @Override
            public void onSuccess(@Nullable String result) {
                System.out.println("成功处理返回结果：" + result);
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.println("处理异常：" + t.getMessage());
            }
        }, Executors.newSingleThreadScheduledExecutor());

        executorService.submit(listenableFutureTask);
    }
}
